<!-- 新增签收 -->
<template>
	<view class="contact">
		<view class="head-context">
			<div class="head-info">
				<view class="row"><text class="head-number" >单号</text><text class="number" disabled>{{items.waybillNumber}}</text></view>
				<view class="row"><text style="letter-spacing:7px">订单号</text><input type="text" class="number" disabled></input></view>
				<view class="row"><text style="letter-spacing:7px">签收人</text><input type="text" class="number" style="background-color: #ebebeb;" v-model="signer"  placeholder="请签收人姓名"></input></view>
				<view class="row"><text style="letter-spacing:1px">签收证件</text><input type="text" class="number" style="background-color: #ebebeb;" v-model="signingDocument" placeholder="请签收人证件号"></input></view>
				<view class="row"><text style="letter-spacing:7px">核销号</text><input type="text" class="number" disabled></input></view>
			</div>
		</view>
		<view class="reason-context">
		</view>
		<view style="margin-left: 10px;margin-top: 10px;">
			<button  @click="handleToNature">签名</button>
		</view>
		<view class="photo-context">
			<view class="photo-text" style="display: flex; align-items: center;justify-content: space-between;">
			    拍照
			    <text style="margin-left: 50px;">
					<checkbox-group @change="checkboxChange">
			        <label class="checkbox-item" style="display: inline-block;">
			            <checkbox value="true" checked="true" class="checkbox-checked" @change="toggleRememberMe" :checked="rememberMe">是否核销</checkbox>
			            
			        </label>
					</checkbox-group>
			    </text>
			    <text class="sum" style="margin-left: 140px;">{{picture.length}}/5</text>
			</view>
			<view style="margin-top: 10px;display: flex;flex-direction: row;">
				<view v-for="(image, index) in picture" :key="index" class="image-item" @click="previewImage(index)" >
					<view class="delete-button" @click.stop="removeImage(index)">
					 <image src="../../../static/叉号.png" style="width: 20px;height: 20px;position: relative;top: -8px;left: 60px;" ></image>
					</view>
				      <image :src="image" style="width: 80px; height: 80px;"></image>
				</view>
			<view class="photo" v-if="picture.length<5">
				<image src="../../../static/相机.png" class="photo-icon" @click="chooseImages">
			</view>
			</view>
		</view>
		<view class="end" >
			<button class="end-button" @click="addClick">保存</button>
		</view>
	</view>
</template>

<script>
	import {getDetails,addSign} from '@/api/sign.js';
	import {sign} from '@/api/delivery.js';
	export default {
		data() {
			return {
				  images: [] ,// 存储选中的图片路径,
				  items:{},
				  signer:'',//签收人姓名
				  signingDocument:'',//签收人证件
				  req:{
					  file:'',
					  fileList:'',
				  },
				  // fileList:[],
				  picture:[],//存储后的路径
				  pictureString:'',
				  imageUrl:'',
				 
			}
		},
		onLoad(options) {
					this.businessId=options.businessId;
					this.phone=options.phone;
					this.type=options.type;
					this.workId=options.workId;
					this.noteId=options.businessId;
					this.waybillNumber=options.waybillNumber;
					this.stockId=options.stockId;
					uni.$on('img', this.handleImageUpdate);
					
			},
			 onUnload() {
			    // 取消监听事件
			    uni.$off('img', this.handleImageUpdate);
			  },
		mounted(){
			// }
			getDetails({businessId: this.businessId}).then(res =>{
				this.items=res.data.data
				this.items.waybillNumber=this.waybillNumber
			}).catch((error) => {
			});
		},
		methods: {
			 removeImage(index) {
			      this.picture.splice(index, 1); // 从数组中删除图片
			    },
			handleImageUpdate(data){
				if(data!=''){
					this.picture.push(data);
					console.log(this.picture)
				}
			},
			previewImage(index) {
			      uni.previewImage({
			        current: index, // 当前显示图片的索引
			        urls: this.picture // 需要预览的图片链接列表
			      });
			    },
			addClick(){
				// console.log(this.type)
				if (!this.signer) {
						uni.showToast({
						        title: '请填写证件人',
						        icon: 'none',
						    });
				        return; // 如果为空，则不执行后续操作
				}
				if(this.type==1 ||this.type==2){
					this.req.businessId=this.noteId
					this.req.wordId=this.workId
					this.req.signer=this.signer
					this.req.signingTime=new Date();
					this.req.type=this.type;
					this.req.stockId=this.stockId,
					this.req.pickerIdNumber=this.signingDocument
					this.req.file=this.picture.toString();
					sign(this.req).then(res =>{
						this.visible = false;
						this.$emit('add-item', 1);
					if(res.data.code===500 || res.data.code===400 || res.data.code===503){
							uni.showToast({
									title: res.data.errorMessage,
									icon: 'error',
							});
						return;
					}else{
						uni.showToast({
							        title: '签收成功',
							        icon: 'success',
						});
						uni.reLaunch({
						    url: '/pagesA/index/order/order?value=3&phone='+this.phone+'&selectedOption='+this.selectedOption // 请注意，这里的url应为相对路径，且以'/'开头
						});
					}
					}).catch((error) => {
					    // 请求失败
					    console.error('签收失败', error);
					    uni.showToast({
					        title: '签收失败，请重试',
					        icon: 'none',
					    });
					});
				}else if(this.type==3){
					
					if(this.picture.length<3){
						uni.showToast({
						        title: '至少需要上传三张照片！',
						        icon: 'none',
						    });
						 return; // 如果为空，则不执行后续操作
					}
					 
					this.req.businessId=this.items.businessId
					this.req.signer=this.signer
					this.req.signingDocument=this.signingDocument
					this.req.type=1
					this.req.signingTime=new Date();
					// this.req.fileList = this.pictureString.toString();
					
					
					// this.req.file = '123459789'
					// this.req.fileList = '9876544'
					this.req.fileList=this.picture.toString();
					this.req.file=this.picture.toString();
					console.log(this.req)
					addSign(this.req).then(res =>{
						this.visible = false;
						this.$emit('add-item', 1);
					
					if(res.data.code===500 || res.data.code===400 || res.data.code===503){
						uni.showToast({
						    title: res.data.errorMessage,
						    icon: 'error',
						});
						return;
					}else{
						uni.showToast({
							        title: '签收成功',
							        icon: 'success',
						});
						uni.reLaunch({
						    url: '/pagesA/index/order/order?value=3&phone='+this.phone+'&selectedOption='+this.selectedOption // 请注意，这里的url应为相对路径，且以'/'开头
						});
					}
					
					}).catch((error) => {
					    // 请求失败
					    console.error('签收成功', error);
					    uni.showToast({
					        title: '签收失败，请重试',
					        icon: 'none',
					    });
					});
				}
			},
			handleToNature(){
				uni.navigateTo({
				    url: '/pages/index/sign/signature' // 请注意，这里的url应为相对路径，且以'/'开头
				});
			},
			
			chooseImages() {
			      uni.chooseImage({
			        count: 9, // 允许选择图片的数量，默认为9
			        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
			        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
			        success: (res) => {
						 // 获取新选择的图片路径
						 console.log(this.images)
							const newImages = res.tempFilePaths;
							this.images = this.images.concat(res.tempFilePaths);
							console.log(this.images)
							// 遍历新选择的图片，并检查是否已上传或已选择
							newImages.forEach((filePath) => {
									// 将选中的图片路径添加到images
								this.uploadFile(filePath);
					  });
			        },
					
			      });
				  
			    },
				uploadFile(filePath) {
				      uni.uploadFile({
				        url: 'https://image.ff5630.com/upload/buy/upload', // 仅为示例，非真实的接口地址
				        filePath: filePath,
				        name: 'file',
				        formData: {
				          user: 'test'
				        },
				        success: (uploadFileRes) => { // 使用箭头函数来保持this的上下文
						try {
						          // 解析服务器返回的JSON响应
						          const responseObj = JSON.parse(uploadFileRes.data);
						          const uploadedImageUrl = responseObj.data; // 假设服务器返回的是图片的URL
						 
						          // 检查并添加URL到picture数组（避免重复）
						          const completeUrl = uploadedImageUrl.startsWith('http://') || uploadedImageUrl.startsWith('https://')
						            ? uploadedImageUrl
						            : 'https://' + uploadedImageUrl; // 根据实际情况调整URL格式
						 
						          if (!this.picture.includes(completeUrl)) {
						            this.picture.push(completeUrl);
						          }
								  console.log(this.picture)
						          console.log('上传成功，图片URL：', completeUrl);
						 
						          // 其他处理上传成功后的逻辑可以在这里添加
						 
						        } catch (error) {
						          console.error('解析上传响应失败：', error);
						        }
				        },
				        fail(err) {
				          console.error('上传失败：', err);
				        }
				      });
					  }
		}
	}
</script>

<style>
@import "sign.css";
</style>
